import React, { createContext, useContext, useReducer } from 'react';
import { AppState } from '../types';
import { initialState } from './initialState';
import { ChatMessage } from '../types/models';

type AppAction = 
  | { type: 'SEND_MESSAGE'; payload: { content: string } }
  | { type: 'RECEIVE_MESSAGE'; payload: ChatMessage }
  | { type: 'SET_ACTIVE_FILE'; payload: { fileId: string } }
  | { type: 'UPDATE_FILE_CONTENT'; payload: { fileId: string; content: string } }
  | { type: 'TOGGLE_SIDEBAR' }
  | { type: 'SELECT_TASK'; payload: { taskId: string } }
  | { type: 'SET_THEME'; payload: { theme: 'dark' | 'light' } }
  | { type: 'ADD_NOTIFICATION'; payload: { message: string; type: 'info' | 'warning' | 'error' | 'success' } }
  | { type: 'MARK_NOTIFICATION_READ'; payload: { notificationId: string } };

function appReducer(state: AppState, action: AppAction): AppState {
  switch (action.type) {
    case 'SEND_MESSAGE':
      return {
        ...state,
        chat: {
          ...state.chat,
          messages: [
            ...state.chat.messages,
            {
              // 由于找不到 generateId 函数，这里使用一个简单的时间戳加上随机数来生成唯一 ID
              id: `${Date.now()}-${Math.floor(Math.random() * 1000)}`,
              content: action.payload.content,
              sender: 'user',
              timestamp: new Date(),
            }
          ],
          isLoading: true
        }
      };
      
    case 'RECEIVE_MESSAGE':
      return {
        ...state,
        chat: {
          ...state.chat,
          messages: [...state.chat.messages, action.payload],
          isLoading: false
        }
      };
      
    case 'SET_ACTIVE_FILE':
      return {
        ...state,
        fileSystem: {
          ...state.fileSystem,
          activeFileId: action.payload.fileId,
          openFileIds: state.fileSystem.openFileIds.includes(action.payload.fileId)
            ? state.fileSystem.openFileIds
            : [...state.fileSystem.openFileIds, action.payload.fileId]
        }
      };
      
    default:
      return state;
  }
}

const AppContext = createContext<{
  state: AppState;
  dispatch: React.Dispatch<AppAction>;
}>({
  state: initialState,
  dispatch: () => null
});

export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(appReducer, initialState);
  
  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  );
};

export const useAppState = () => {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useAppState must be used within an AppProvider');
  }
  return context;
};